<template>
  <view class="page_root" data-page-name="首页" data-page-identification="m_fzo7koam7h">
    <!-- UNI_APP_EXEGESIS_START NAVIGATION_TEMPLATE UNI_APP_EXEGESIS_END -->
    <!-- begin vid_5j6lieg03w 自定义模板_hbrapurxmy -->
    <u-mask :show="state.loading">
      <view class="warp">
        <view class="rect" @tap.stop>加载中....</view>
      </view>
    </u-mask>
    <!-- 工时管理首页 -->
    <u-popup v-model="state.workHourActionShow" mode="center" width="100%" height="100%">
      <view class="worker-hour-body">
        <u-navbar
          back-icon-color="#fff"
          title="工时管理"
          title-color="#fff"
          :custom-back="navbarBackFn"
          :border-bottom="false"
        >
        </u-navbar>
        <view class="bot-bgc"></view>
        <view class="form-title"
          >高效记录的<br />
          管理您的工作时间</view
        >
        <view class="rb-type">
          <view class="cy-add-icon" @click="actionClick(0)">
            <view class="add-label">新建产研交付日报</view>
            <view class="add-value">项目研发流程中的具体工作事项</view>
          </view>
          <view class="gd-add-icon" @click="actionClick(3)">
            <view class="add-label">新建工单日报</view>
            <view class="add-value">工单处理过程中的具体工时</view>
          </view>
          <view class="qt-add-icon">
            <view class="add-label" @click="actionClick(1)">新建其他日报</view>
            <view class="add-value">会议、休假等具体工作事项</view>
          </view>
          <u-section
            title="最近日报记录"
            sub-title="查看更多"
            style="margin-bottom: 24rpx"
            @click="actionClick(2)"
          ></u-section>
          <view class="hour-item" v-for="(item, index) in state.workerHourData" :key="index.id">
            <view class="hour-item-left">
              <view class="worker-icon"></view>
              <view class="worker-msg">
                <view class="hour-item-msg-label">{{ dailyTypeMap[item.dailyType] }}</view>
                <view class="hour-item-msg-value">{{ item.submissionTime }}</view>
              </view>
            </view>
            <view class="hour-item-right">
              <u-circle-progress
                active-color="#3366FF"
                :percent="calcPercent(item.workingHours)"
                width="80"
                border-width="8"
              >
                <view class="u-progress-content">
                  <text class="u-progress-info">{{ item.workingHours }}h</text>
                </view>
              </u-circle-progress>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
    <view class="body" v-if="pageAllRight">
      <view class="top-title">欢迎回来!</view>
      <view class="date-time">今天是{{ state.time }} {{ state.week }} {{ state.clock }}</view>
      <view class="menu-body" v-for="(item, index) in menuList" :key="index">
        <view
          :class="['menu-item', isDisabled(menu) ? 'disabled' : '']"
          v-for="(menu, menuIndex) in item.menuItemList"
          :key="menuIndex"
          @click="handleJumpPage(menu.class, isDisabled(menu))"
        >
          <view :class="menu.class"></view>
          <view class="menu-message">
            <view class="menu-title1">{{ menu.title1 }}</view>
            <view class="menu-title2">{{ menu.title2 }}</view>
          </view>
        </view>
      </view>
    </view>
    <!-- end vid_5j6lieg03w 自定义模板_hbrapurxmy -->
  </view>
</template>
<script setup>
  import {
    ref,
    reactive,
    toRaw,
    markRaw,
    watch,
    computed,
    onBeforeMount,
    onMounted,
    onBeforeUnmount,
    onUnmounted,
    onActivated,
    onDeactivated,
    getCurrentInstance,
  } from 'vue';
  import { useRoute } from 'vue-router';
  const route = useRoute();
  import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
  import {
    cloneDeep,
    localGet,
    traversalTreeStructure,
    set,
    checkCaseCondition,
    throttle,
    merge,
    debounce,
    getGridStyle,
    getCellRenderAble,
    formulaStrategy,
    getApplicationId,
    getComponentParamsValue,
    get as lodashGet,
  } from '@/utils/index';
  import {
    isEqual,
    isNullOrEmpty,
    isEmptyArr,
    isArray,
    isEmpty,
    isNullOrUnDef,
    isContained,
  } from '@/utils/is';
  import { CovertOptions, getChartsDataSourceConvert } from '@/utils/chart';
  import {
    propertyFormatByNumber,
    propertyFormatByPercentage,
    propertyFormatByDate,
    parseSubFromDataList,
  } from '@/utils/format';
  import { checkCommonCondition, getResultByCurrentCommonCondition } from '@/utils/formCondition';
  import { FormFormat } from '@/utils/formFormat';
  import { customAddWaterMarkFunc, generateWaterMarkText } from '@/utils/addWaterMark';
  import dayjs from 'dayjs';
  import hashSum from 'hash-sum';
  import {
    onPullDownRefresh,
    onLoad,
    onReady,
    onShow,
    onHide,
    onPageScroll,
    onUnload,
  } from '@dcloudio/uni-app';
  /*** UNI_APP_EXEGESIS ***
    import { handleRedirect, permission, parseJson } from '@/utils/common';
    import { onPullDownRefresh, onLoad, onReady, onShow, onHide, onPageScroll, onUnload } from '@dcloudio/uni-app';
    import { BroadcastMessage } from '@/utils/BroadcastMessage';
    import { sendToken } from "@/hooks/useIframeToken";
    *** UNI_APP_EXEGESIS ***/
  import { handleRedirect, permission, parseJson } from '@/utils/common';
  // ---------------------------- 属性定义 ----------------------------
  const sourceId = 'page3000001233';

  // 获取传入的流程ID和组件参数
  const props = defineProps({
    processInstanceId: {
      type: [String, Number, Boolean],
      default: undefined,
    },
    hideNav: {
      type: [Boolean],
      default: undefined,
    },
  });

  // 组件参数默认值
  const componentParamsDefaultProps = {};

  // 是否显示菜单按钮
  const isMenuIconShow = false;
  // NAVIGATION_MENU
  const handleShowNavigation = () => {};

  let isProcessState = ref(false);

  const setTimeOutList = [];

  const vid_5j6lieg03w_props = reactive({
    code: '',
  });

  // ============================ 属性定义 ============================

  // ---------------------------- 元素数据引用 ----------------------------
  // 组件 自定义模板_hbrapurxmy ref 的引用
  const vid_5j6lieg03w_ref = ref(null);
  // 动态key的map
  const fieldTypeMap = {};
  // 动态key的map
  const refMap = { vid_5j6lieg03w_ref };

  const showState = reactive({
    vid_5j6lieg03w_visible: true,
  });
  // ============================ 元素数据引用 ============================

  // ---------------------------- 数据 ----------------------------

  // ============================ 数据 ============================

  // ---------------------------- 方法 ----------------------------
  // ---------------------------- 页面数据 ----------------------------

  // ============================ 页面数据 ============================

  // ---------------------------- 数据字典 ----------------------------

  // ============================ 数据字典 ============================

  // ---------------------------- 响应 ----------------------------

  // ============================ 响应 ============================

  // ---------------------------- 函数 ----------------------------

  // 自定义函数 返回上一页
  const customFunction_goBack_v6glt46b1g = (params) => {
    uni.navigateBack();
  };

  // ============================ 函数 ============================

  // ---------------------------- 页面参数 ----------------------------

  const pageParameter_state = reactive({
    processInstanceId: undefined,
  });

  // ============================ 页面参数 ============================

  // ---------------------------- 组件事件处理方法 ----------------------------

  // ============================ 组件事件处理方法 ============================

  // ============================ 方法 ============================

  // ---------------------------- 生命周期 ----------------------------
  /*** UNI_APP_EXEGESIS ***
        // 获取上一层传递的数据
        const workflowChannel = new BroadcastMessage('WORKFLOW');
        workflowChannel.publish({ status: 'Ready' });
        workflowChannel.subscribe((data) => {
          if (data) {
            isProcessState.value = (window.self !== window.parent && data.type === 'hideHeader');
          }
        });
        *** UNI_APP_EXEGESIS ***/

  const pageScrollTop = ref(0);

  // *** PREVIEW_EXEGESIS ***
  onMounted(() => {
    setPageParams(route.query);
    // 设置表单的rule
    try {
    } catch {
      // do nothing
    }
  });
  // *** PREVIEW_EXEGESIS *** //

  /*** UNI_APP_EXEGESIS ***
    const routeOption = ref({})
    onLoad((option) => {
      routeOption.value = option;
    });
    onReady(() => {
      setPageParams(routeOption.value)
      // 设置表单的rule
      try{

      }catch{
          // do nothing
      }
    });
    // 图表刷新标记
    const uChartsReshowFlag = ref(false);
    onHide(() => { // 页面隐藏后标记置为false(如果不置为false无法触发图表更新)
        uChartsReshowFlag.value = false
    })
    onShow(() => {
        uChartsReshowFlag.value = true; // 页面激活后,标记置为true

        setPageParams(routeOption.value)
    })
    onPageScroll(e => {
        pageScrollTop.value = e.scrollTop
    });
    *** UNI_APP_EXEGESIS ***/

  let setPageParams = (routerParam) => {
    const pageParams = [{ dataType: 'STRING', name: 'processInstanceId' }];
    const strategyMap = {
      STRING: (param, paramValue) => {
        pageParameter_state[param.name] = paramValue;
      },
      BOOLEAN: (param, paramValue) => {
        if ('true' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = true;
        } else if ('false' === (paramValue || '').toLowerCase()) {
          pageParameter_state[param.name] = false;
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      NUMBER: (param, paramValue) => {
        if (!isNaN(paramValue)) {
          pageParameter_state[param.name] = Number(paramValue);
        } else {
          // TODO: 是否要支持toast
          console.error('参数传入错误！类型不匹配！');
        }
      },
      ARRAY: (param, paramValue) => {
        if (isNullOrUnDef(paramValue) || !paramValue || paramValue === 'undefined') {
          // default value
          pageParameter_state[param.name] = [];
        } else if (paramValue.trim().startsWith('[') && paramValue.trim().endsWith(']')) {
          try {
            pageParameter_state[param.name] = JSON.parse(decodeURI(paramValue));
          } catch (error) {
            console.error('参数解析失败 ', error);
          }
        } else {
          console.error('参数传入错误！类型不匹配！');
        }
      },
    };
    pageParams.forEach((param) => {
      strategyMap[param.dataType](param, routerParam[param.name]);
    });
  };

  onUnmounted(() => {
    // 销毁定时器
    setTimeOutList.forEach(({ repeat, timer }) => {
      repeat ? clearInterval(timer) : clearTimeout(timer);
    });
  });

  /*** UNI_APP_EXEGESIS ***
    onPullDownRefresh(() => {
      // 下拉刷新
      setTimeout(() => {
          uni.stopPullDownRefresh()
      }, 1000)
    })
    *** UNI_APP_EXEGESIS ***/

  // ============================ 生命周期 ============================

  // ---------------------------- 数据关联处理 ----------------------------
  // ---------------------------- 组件数据同步 ----------------------------

  // ============================ 组件数据同步 ============================
  //
  // ============================ 数据关联处理 ============================

  // ---------------------- 不同组件自定义的处理逻辑 ---------------------

  // ====================== 不同组件自定义的处理逻辑 ======================

  // ================================定制化逻辑========================================
  import 'dayjs/locale/zh-cn';
  onMounted(() => {
    state.time = dayjs().locale('zh-cn').format('YYYY年MM月DD日');
    state.week = dayjs().locale('zh-cn').format('dddd');
  });
  import { Button, showFailToast } from 'vant';
  import 'vant/lib/index.css';
  // ✅ 获取当前页面的 app 实例上下文
  const { appContext } = getCurrentInstance();

  // ✅ 在当前页面作用域注册 Vant 组件
  appContext.app.component('van-button', Button);
  onMounted(() => {
    setPageStyle('home-page');
    getUserInfo();
  });

  function setPageStyle(newClass) {
    // #ifdef H5
    // 仅在 H5 执行
    const appDiv = document.querySelector('#app');
    if (appDiv) {
      appDiv.className = '';

      // 再添加当前需要的类
      if (newClass) {
        appDiv.classList.add(newClass);
      }
    }

    const topHeader = document.querySelector('.uni-page-head');
    if (topHeader) topHeader.remove();

    const wrapper = document.querySelector('uni-page-wrapper');
    if (wrapper) wrapper.style.height = '100%';
    // #endif

    // #ifdef MP
    // 小程序端执行（如果你要做兼容逻辑，可以写这里）
    console.log('当前是小程序环境，不需要处理头部或背景');
    // #endif
  }

  const state = reactive({
    time: undefined,
    week: undefined,
    clock: undefined,
    userInfo: {},
    userMenu: {},
    workHourActionList: [
      {
        text: '新建产研交付日报',
      },
      {
        text: '新建其他日报',
      },
      {
        text: '我的日报',
      },
    ],
    workHourActionShow: false,
    workerHourData: [],
    loading: false,
  });

  const menuList = [
    {
      menuItemList: [
        {
          class: 'work-hour',
          title1: '工时管理',
          title2: '记录工作时间',
          disabled: false,
        },
        {
          class: 'crm-meet',
          title1: '客成部例会记录',
          title2: '管理例会信息',
          disabled: false,
        },
      ],
    },
    {
      menuItemList: [
        {
          class: 'work-order',
          title1: '工单管理',
          title2: '处理服务工单',
          disabled: false,
        },
        {
          class: 'employee-performance',
          title1: '员工绩效',
          title2: '每月主管评分',
          disabled: false,
        },
      ],
    },
    {
      menuItemList: [
        {
          class: 'task',
          title1: '任务管理',
          title2: '查看和管理任务',
          disabled: true,
        },
        {
          class: 'approve',
          title1: '审批管理',
          title2: '处理审批事项',
          disabled: true,
        },
      ],
    },
  ];
  const permissionMap = {
    'crm-meet': '50000005_mijiu1cxt0',
    'employee-performance': '50000005_3rut95b8oz',
  };
  function isDisabled(menu) {
    // 如果menu本身写死disabled是true，优先返回true（没开发完）
    if (menu.disabled) return true;
    if (['crm-meet', 'employee-performance'].includes(menu.class)) {
      return !findCode(state.userMenu, permissionMap[menu.class]);
    }
    return false;
  }
  function calcPercent(hours) {
    if (!hours) return 0;
    const maxHours = 8;
    return hours >= maxHours ? 100 : (hours / maxHours) * 100;
  }

  const dailyTypeMap = {
    1: '产研交付日报',
    3: '其他日报',
    4: '项目日报',
    6: '工单日报',
  };
  const jumpPageMap = {
    'crm-meet': 'Page3000001243/Page3000001243',
    'work-order': 'Page3000001010/Page3000001010',
    'employee-performance': 'Page3000001244/Page3000001244',
    task: 'Page3000000251/Page3000000251',
    approve: 'Page3000000258/Page3000000258',
    0: 'Page3000000037/Page3000000037',
    1: 'Page50001907/Page50001907',
    2: 'Page3000001238/Page3000001238',
    3: 'Page3000001261/Page3000001261',
  };
  const pageAllRight = ref(false);
  function getUserInfo() {
    get('/base/api/v1/user/userinfo').then((data) => {
      if (data.status !== 'success') {
        state.userInfo = {};
        showFailToast('权限获取失败！请刷新重试');
        pageAllRight.value = true;
        return;
      }
      state.userInfo = data.data.userItem;
      state.userMenu = data.data.resourcesItems;
      pageAllRight.value = true;
      console.log(findCode(state.userMenu, '50000005_mijiu1cxt0'), '客户');
      console.log(findCode(state.userMenu, '50000005_3rut95b8oz'), '绩效');
    });
  }
  function handleJumpPage(page, disabled) {
    if (['work-order1', 'approve', 'task'].includes(page)) {
      showFailToast('暂未开放');
      return;
    }

    if (page === 'work-hour') {
      getRecordList();
    }
    if (disabled) {
      showFailToast('暂无权限');
      return;
    }
    handleRedirect(`/pages/${jumpPageMap[page]}?`);
  }
  function findCode(tree, targetCode) {
    if (!Array.isArray(tree)) return false;

    for (const node of tree) {
      // 当前节点匹配
      if (node?.data?.code === targetCode) {
        return true;
      }

      // 有 children 继续递归
      if (node.children && findCode(node.children, targetCode)) {
        return true;
      }
    }

    return false;
  }

  function navbarBackFn() {
    state.workHourActionShow = false;
  }

  onShow(() => {
    const shouldShowPopup = sessionStorage.getItem('shouldShowWorkHourPopup');
    if (shouldShowPopup === 'true') {
      getRecordList();
      sessionStorage.removeItem('shouldShowWorkHourPopup');
    }
  });
  function actionClick(index) {
    sessionStorage.setItem('shouldShowWorkHourPopup', 'true');
    state.workHourActionShow = false;
    handleRedirect(`/pages/${jumpPageMap[index.toString()]}?`);
  }
  setInterval(() => {
    state.clock = dayjs().format('HH:mm:ss');
  });
  function getRecordList() {
    state.loading = true;
    post('/solution-ppm/api/v2/built-in-system-ppm/daily/list', {
      pageNo: 1,
      pageSize: '2',
      reportedBy: state.userInfo.name,
    })
      .then((data) => {
        state.workerHourData = data.data.dataList;
        state.workHourActionShow = true;
      })
      .finally(() => {
        state.loading = false;
      });
  }
</script>
<style lang="less" scoped>
  .page_root {
    min-height: 100%;
    box-sizing: border-box;
    overflow: auto;
  }
  //   工单
  .page_root {
    background-image: url('http://10.40.0.33:9001/file-storage/538984691473397760-source.png');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center;
    box-sizing: border-box;
    overflow: auto;
  }
  .body {
    padding: 64rpx;
    height: 100%;
  }
  .top-title {
    font-family: AlimamaShuHeiTi-Bold;
    font-size: 64rpx;
    color: #ffffff;
    font-weight: 700;
    margin-bottom: 18rpx;
  }
  .date-time {
    font-family: PingFangSC-Medium;
    font-size: 28rpx;
    color: #ffffff;
    font-weight: 600;
    margin-bottom: 78rpx;
  }
  .menu-body {
    display: flex;
    justify-content: space-between;
    gap: 32rpx;
    margin-bottom: 32rpx;
  }
  .menu-item {
    width: 295rpx;
    height: 340rpx;
    background-image: url('http://10.40.0.33:9001/file-storage/538984776414345216-source.png');
    background-size: cover;
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 40rpx 0 32rpx 0;
    justify-content: space-between;
    border-radius: 32rpx;
  }
  .work-hour,
  .crm-meet,
  .work-order,
  .employee-performance,
  .task,
  .approve {
    width: 135rpx;
    height: 135rpx;
    background-size: cover;
  }
  .work-hour {
    background-image: url('http://10.40.0.33:9001/file-storage/538984759725209600-source.png');
  }
  .crm-meet {
    background-image: url('http://10.40.0.33:9001/file-storage/538984798207948800-source.png');
  }
  .work-order {
    background-image: url('http://10.40.0.33:9001/file-storage/538984725120104448-source.png');
  }
  .employee-performance {
    background-image: url('http://10.40.0.33:9001/file-storage/538984861332224000-source.png');
  }
  .task {
    background-image: url('http://10.40.0.33:9001/file-storage/538984828035741696-source.png');
  }
  .approve {
    background-image: url('http://10.40.0.33:9001/file-storage/538984845138016256-source.png');
  }
  .menu-message {
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .menu-title1 {
    font-size: 36rpx;
    color: #262626;
    font-weight: 600;
  }
  .menu-title2 {
    font-size: 28rpx;
    color: #595959;
    font-weight: 400;
  }
  /* 禁用状态样式 */
  .menu-item.disabled {
    // pointer-events: none;
    position: relative;
  }

  /* 添加灰色遮罩 */
  .menu-item.disabled::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.7);
    z-index: 1;
    border-radius: inherit;
  }

  /* 图标和文字变灰 */
  .menu-item.disabled .work-hour,
  .menu-item.disabled .crm-meet,
  .menu-item.disabled .work-order,
  .menu-item.disabled .employee-performance,
  .menu-item.disabled .task,
  .menu-item.disabled .approve {
    filter: grayscale(100%) brightness(0.7);
  }

  .menu-item.disabled .menu-title1,
  .menu-item.disabled .menu-title2 {
    color: #999;
    position: relative;
    z-index: 2;
  }

  /* 添加禁用图标 */
  .menu-item.disabled::after {
    content: '🔒';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 48rpx;
    z-index: 3;
    opacity: 0.8;
  }
  .worker-hour-body {
    background-image: url('http://10.40.0.33:9001/file-storage/540437262415247360-source.png');
    background-size: cover;
  }

  .bot-bgc {
    width: 220rpx;
    height: 200rpx;
    position: absolute;
    background-image: url('http://10.40.0.33:9001/file-storage/540433567558481920-source.png');
    background-size: cover;
    background-position: to center;
    z-index: 2;
    right: 10rpx;
    top: 80rpx;
  }
  :deep(.u-navbar) {
    background-color: transparent !important;
    padding: 0 40rpx 0 0;
    border: none;
  }
  .form-title {
    font-size: 36rpx;
    color: #ffffff;
    font-weight: 600;
    padding-left: 64rpx;
    margin-bottom: 30rpx;
  }
  .rb-type {
    position: relative;
    overflow: hidden;
    padding: 96rpx 64rpx;
    background-image: url('http://10.40.0.33:9001/file-storage/540432939803293696-source.png');
    background-size: cover;
    height: calc(100vh - 260rpx);
  }
  .cy-add-icon,
  .gd-add-icon,
  .qt-add-icon {
    padding: 46rpx 61rpx;
    height: 200rpx;
    background-size: cover;
    margin-bottom: 26rpx;
  }
  .cy-add-icon {
    background-image: url('http://10.40.0.33:9001/file-storage/540438199078828032-source.png');
  }
  .gd-add-icon {
    background-image: url('http://10.40.0.33:9001/file-storage/540438246805813248-source.png');
    margin-bottom: 32rpx;
  }
  .qt-add-icon {
    background-image: url('http://10.40.0.33:9001/file-storage/540438279078885376-source.png');
    margin-bottom: 38rpx;
  }
  .add-label {
    font-size: 36rpx;
    color: #262626;
    font-weight: 500;
    padding-left: 160rpx;
  }
  .add-value {
    font-size: 24rpx;
    color: rgba(0, 0, 0, 0.45);
    font-weight: 400;
    padding-left: 160rpx;
  }
  :deep(.u-section__right-info) {
    font-size: 24rpx;
    color: rgba(0, 0, 0, 0.85) !important;
    font-weight: 400;
  }
  .rb-type :deep(.uicon-arrow-right) {
    color: rgba(0, 0, 0, 0.85) !important;
  }
  .hour-item {
    padding: 32rpx 41rpx;
    border-radius: 24rpx;
    background-image: linear-gradient(180deg, #ffffff 4%, rgba(253, 254, 255, 0.5) 100%);
    border: 2rpx solid rgba(255, 255, 255, 1);
    display: flex;
    justify-content: space-between;
  }
  .hour-item-left {
    display: flex;
    gap: 32rpx;
  }
  .worker-icon {
    background-image: url('http://10.40.0.33:9001/file-storage/540440047523280896-source.png');
    background-size: cover;
    width: 80rpx;
    height: 90rpx;
  }
  .hour-item-msg-label {
    font-size: 32rpx;
    color: #262626;
    font-weight: 500;
  }
  .hour-item-msg-value {
    font-size: 24rpx;
    color: rgba(0, 0, 0, 0.45);
    font-weight: 400;
  }
  .u-progress-info {
    font-size: 24rpx;
    color: #3366ff;
    font-weight: 600;
    background-image: linear-gradient(180deg, #ffffff 4%, rgba(253, 254, 255, 0.5) 100%);
  }
  .hour-item {
    margin-bottom: 20rpx;
  }
  .warp {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  .rect {
    color: #fff;
  }
</style>
